<template>
  <div class="admin-dashboard">
    <h1>{{ t('message.adminDashboard') }}</h1>
    
    <div class="stats-grid">
      <div class="stat-card">
        <h3>{{ t('message.totalUsers') }}</h3>
        <p class="stat-number">{{ stats.totalUsers }}</p>
      </div>
      <div class="stat-card">
        <h3>{{ t('message.activeTeachers') }}</h3>
        <p class="stat-number">{{ stats.activeTeachers }}</p>
      </div>
      <div class="stat-card">
        <h3>{{ t('message.pendingTeachers') }}</h3>
        <p class="stat-number">{{ stats.pendingTeachers }}</p>
      </div>
      <div class="stat-card">
        <h3>{{ t('message.totalSessions') }}</h3>
        <p class="stat-number">{{ stats.totalSessions }}</p>
      </div>
    </div>

    <div class="dashboard-content">
      <div class="recent-sections">
        <div class="recent-users">
          <h2>{{ t('message.recentUsers') }}</h2>
          <div v-if="recentUsers.length === 0" class="empty-state">
            {{ t('message.noRecentUsers') }}
          </div>
          <table v-else class="data-table">
            <thead>
              <tr>
                <th>{{ t('message.username') }}</th>
                <th>{{ t('message.email') }}</th>
                <th>{{ t('message.role') }}</th>
                <th>{{ t('message.registrationDate') }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="user in recentUsers" :key="user.userId">
                <td>{{ user.username }}</td>
                <td>{{ user.email }}</td>
                <td>{{ user.roleId }}</td>
                <td>{{ formatDate(user.createdAt) }}</td>
              </tr>
            </tbody>
          </table>
        </div>

        <div class="pending-teachers">
          <h2>{{ t('message.pendingTeacherApprovals') }}</h2>
          <div v-if="pendingTeachers.length === 0" class="empty-state">
            {{ t('message.noPendingTeachers') }}
          </div>
          <table v-else class="data-table">
            <thead>
              <tr>
                <th>{{ t('message.username') }}</th>
                <th>{{ t('message.email') }}</th>
                <th>{{ t('message.university') }}</th>
                <th>{{ t('message.actions') }}</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="teacher in pendingTeachers" :key="teacher.userId">
                <td>{{ teacher.username }}</td>
                <td>{{ teacher.email }}</td>
                <td>{{ teacher.university || '-' }}</td>
                <td>
                  <button class="btn btn-success" @click="approveTeacher(teacher.userId)">
                    {{ t('message.approve') }}
                  </button>
                  <button class="btn btn-danger" @click="rejectTeacher(teacher.userId)">
                    {{ t('message.reject') }}
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useAuthStore } from '@/stores/auth';
import axios from 'axios';
import { useI18n } from 'vue-i18n';

export default {
  name: 'Overview',
  setup() {
    const { t } = useI18n();
    const stats = ref({
      totalUsers: 0,
      activeTeachers: 0,
      pendingTeachers: 0,
      totalSessions: 0
    });
    
    const recentUsers = ref([]);
    const pendingTeachers = ref([]);
    
    const authStore = useAuthStore();
    
    // API calls to fetch actual data
    const loadDashboardData = async () => {
      try {
        // Fetch dashboard statistics
        const statsResponse = await axios.get('/api/admin/stats');
        const statsData = statsResponse.data.data || {};
        stats.value = {
          totalUsers: statsData.totalUsers || 0,
          activeTeachers: statsData.activeTeachers || 0,
          pendingTeachers: statsData.pendingTeachers || 0,
          totalSessions: statsData.totalSessions || 0
        };
        
        // Fetch recent users
        const usersResponse = await axios.get('/api/admin/users/recent');
        recentUsers.value = (usersResponse.data.data || []).slice(0, 5);
        
        // Fetch pending teachers
        const teachersResponse = await axios.get('/api/admin/teachers/pending');
        pendingTeachers.value = teachersResponse.data.data || [];
      } catch (error) {
        console.error('Error loading dashboard data:', error);
        
        // Fallback to mock data if API fails
        stats.value = {
          totalUsers: 1247,
          activeTeachers: 128,
          pendingTeachers: 23,
          totalSessions: 4562
        };
        
        recentUsers.value = [
          { userId: '1', username: 'teacher1', email: 'teacher1@youke.com', roleId: 'TEACHER', createdAt: '2025-11-01T10:30:00' },
          { userId: '2', username: 'parent1', email: 'parent1@youke.com', roleId: 'PARENT', createdAt: '2025-11-02T14:20:00' },
          { userId: '3', username: 'teacher2', email: 'teacher2@youke.com', roleId: 'TEACHER', createdAt: '2025-11-03T09:15:00' },
          { userId: '4', username: 'admin1', email: 'admin1@youke.com', roleId: 'ADMIN', createdAt: '2025-11-04T16:45:00' },
          { userId: '5', username: 'parent2', email: 'parent2@youke.com', roleId: 'PARENT', createdAt: '2025-11-05T11:30:00' }
        ];
        
        pendingTeachers.value = [
          { userId: '6', username: 'newteacher1', email: 'newteacher1@youke.com', university: 'Beijing University' },
          { userId: '7', username: 'newteacher2', email: 'newteacher2@youke.com', university: 'Shanghai Jiao Tong University' },
          { userId: '8', username: 'newteacher3', email: 'newteacher3@youke.com', university: 'Tsinghua University' }
        ];
      }
    };
    
    const approveTeacher = async (teacherId) => {
      try {
        await axios.post(`/api/admin/teachers/${teacherId}/approve`);
        
        // Update UI
        pendingTeachers.value = pendingTeachers.value.filter(t => t.userId !== teacherId);
        stats.value.pendingTeachers -= 1;
        stats.value.activeTeachers += 1;
      } catch (error) {
        console.error('Error approving teacher:', error);
        alert('Failed to approve teacher: ' + error.message);
      }
    };
    
    const rejectTeacher = async (teacherId) => {
      try {
        await axios.post(`/api/admin/teachers/${teacherId}/reject`);
        
        // Update UI
        pendingTeachers.value = pendingTeachers.value.filter(t => t.userId !== teacherId);
        stats.value.pendingTeachers -= 1;
      } catch (error) {
        console.error('Error rejecting teacher:', error);
        alert('Failed to reject teacher: ' + error.message);
      }
    };
    
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString();
    };
    
    onMounted(() => {
      loadDashboardData();
    });
    
    return {
      stats,
      recentUsers,
      pendingTeachers,
      approveTeacher,
      rejectTeacher,
      formatDate,
      t
    };
  }
};
</script>

<style scoped>
.overview {
  padding: 0;
  max-width: 100%;
  margin: 0;
}

.overview h1 {
  color: #2c3e50;
  margin: 0;
  text-align: left;
  font-size: 1.8rem;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.stat-card {
  background: white;
  border-radius: 6px;
  padding: 1rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.stat-card h3 {
  margin: 0 0 0.5rem 0;
  color: #7f8c8d;
  font-size: 0.9rem;
}

.stat-number {
  font-size: 1.6rem;
  font-weight: bold;
  color: #3498db;
  margin: 0;
}

.charts-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1.5rem;
  margin-bottom: 1.5rem;
}

.chart-container {
  background: white;
  border-radius: 6px;
  padding: 1rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.chart-container h2 {
  margin-top: 0;
  color: #2c3e50;
  text-align: center;
  font-size: 1.1rem;
}

.chart-wrapper {
  height: 220px;
  position: relative;
}

.dashboard-content {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.recent-sections {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1.5rem;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 0.5rem;
  background: white;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.data-table th,
.data-table td {
  padding: 0.75rem;
  text-align: left;
  border-bottom: 1px solid #ecf0f1;
}

.data-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #2c3e50;
  font-size: 0.9rem;
}

.data-table tr:last-child td {
  border-bottom: none;
}

.data-table tr:hover {
  background-color: #f8f9fa;
}

.btn {
  padding: 0.4rem 0.8rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.85rem;
}

.btn-success {
  background-color: #2ecc71;
  color: white;
}

.btn-success:hover {
  background-color: #27ae60;
}

.btn-danger {
  background-color: #e74c3c;
  color: white;
}

.btn-danger:hover {
  background-color: #c0392b;
}

.empty-state {
  text-align: center;
  padding: 1.5rem;
  color: #7f8c8d;
  font-style: italic;
  font-size: 0.9rem;
}

@media (max-width: 768px) {
  .recent-sections,
  .charts-section {
    grid-template-columns: 1fr;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .chart-wrapper {
    height: 200px;
  }
  
  .chart-wrapper {
    height: 200px;
  }
  
  .overview h1 {
    font-size: 1.5rem;
  }
}
</style>